import { SSLib } from '@lib/SSLib';

export class IssuesRemind {
    // constructor() {

    // }

    /** 开始定时检测 */
    public static StartIssuesRemindCheck() {
        setTimeout(() => {
            checkIssues();    
        }, 200);
        
        setInterval(() => {
            if (new Date().getHours() >= 16) {
                // 时间在16点以后，才进行触发判断
                checkIssues(); 
            }
        }, 10 * 60 * 1000);
    }

    public static GetRemindIssues(cb: (data: IssueModel[]) => void, forwardDay: number = 0) {
        let targetDate = new Date();

        if (forwardDay > 0) {
            targetDate = new Date(new Date().setDate(new Date().getDate() + forwardDay));
        }

        let targetDateStr = SSLib.dateFormatter(targetDate, "yyyy-MM-dd");

        SSLib.gGet('/api/v4/issues?per_page=200&state=opened&scope=assigned_to_me', (data: IssueModel[]) => {
            let matches = data.filter(item => {
                if (!item.due_date) {
                    return;
                }
    
                return item.due_date <= targetDateStr;
            });
    
            cb(matches);
        });
    }
}

/**  */
function checkIssues() {
    IssuesRemind.GetRemindIssues(data => {
        let infoArr = data.map(item => {
            return { title: item.title, web_url: item.web_url }
        });

        if (infoArr.length <= 0) {
            return;
        }

        let iconUrl = data[0].assignee.avatar_url;

        let content = data.map(item => item.title).join('\r\n');
        let issuesUrl = data[0].web_url;

        let notifications = {
            type: "slayer-issues-remind",
            issuesUrl,
            random: Math.random()
        };
        let notificationId = JSON.stringify(notifications);
        chrome.notifications.create(notificationId, {
            type: "basic",
            iconUrl,
            title: "存在即将超期的议题",
            message: content,
            buttons: [{
                title: '查看详情'
            }]
        });

        chrome.browserAction.setBadgeText({ text: "" + infoArr.length });
    });
}

chrome.notifications.onButtonClicked.addListener(notificationId => {
    let data = JSON.parse(notificationId);
    let issuesUrl = data.issuesUrl;

    chrome.tabs.create({ url: issuesUrl }, () => { });
})

class IssueModel {
    public title: string;

    public web_url: string;

    public due_date: string;

    public labels: string[];

    public assignee: { 
        avatar_url: string
    }
}
